package com.inwavetech.os.util.field;

import android.widget.TextView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Objects;

/**
 * Created by jgskin on 2/14/14.
 */
public class BigDecimalField extends BaseTextField {

    private final DecimalFormat formatter;

    public BigDecimalField(TextView view, DecimalFormat formatter) {
        super(view);
        this.formatter = formatter;
    }

    @Override
    public boolean isValid() {
        if (super.isValid()) {
            if (getValue() != null) {
                return true;
            }
        }

        view.setError("Valor inválido");
        return false;
    }

    public BigDecimal getValue() {
        String value = (String) super.getValue();

        try {
            return new BigDecimal(value.replace(".", "").replace(",", "."));
        } catch (NumberFormatException e) {
            view.setError("Valor inválido");

            return null;
        }

    }

    @Override
    public void setValue(Object value) {
        if (value != null) {
            view.setText(formatter.format(value));
        }
    }

}
